package com.by.hellosecurityoauth2.service.impl;

import com.by.hellosecurityoauth2.controller.request.AuthorityRequestBean;
import com.by.hellosecurityoauth2.domain.TAuthority;
import com.by.hellosecurityoauth2.domain.repository.TAuthorityRepository;
import com.by.hellosecurityoauth2.service.AuthorityService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;

/**
 * @author 白羽
 * @Date 2022-12-13 09:15:55
 */
@Service
@Transactional(value = "transactionManager", isolation = Isolation.REPEATABLE_READ,
        propagation = Propagation.REQUIRED)
public class AuthorityServiceImpl implements AuthorityService {

    private final TAuthorityRepository authorityRepository;
    
    public AuthorityServiceImpl(TAuthorityRepository authorityRepository) {
        this.authorityRepository = authorityRepository;
    }
    
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TAuthority findById(Long id) {
        return authorityRepository.findById(id).orElse(null);
    }

    /**
     * 查询多条数据
     *
     * @param page 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override 
    public Page<TAuthority> list(int page, int limit) {
        Pageable pageable = PageRequest.of(page, limit, Sort.by(Sort.Direction.DESC, "id"));
        return authorityRepository.findAll((Specification<TAuthority>) (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            return predicate;
        }, pageable);
    }

    /**
     * 新增数据
     *
     * @param bean 实例对象
     * @return 实例对象
     */
    @Override
    public TAuthority create(AuthorityRequestBean bean) {
        TAuthority authority = new TAuthority();
        BeanUtils.copyProperties(bean, authority);
        return authorityRepository.save(authority);
    }

    /**
     * 修改数据
     * @param id 主键
     * @param bean 实例对象
     * @return 实例对象
     */
    @Override
    public TAuthority updateById(Long id, AuthorityRequestBean bean) {
        TAuthority authority = findById(id);
        BeanUtils.copyProperties(bean, authority);
        return authorityRepository.save(authority);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     */
    @Override 
    public void deleteById(Long id) {
        authorityRepository.deleteById(id);
    }
    
}